package com.cc.flyingfish.advice;

import com.cc.flyingfish.annotation.IgnoreResponseAdvice;
import com.cc.flyingfish.vo.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import static com.cc.flyingfish.vo.CommonResponse.SUCCESS;

/**
 * @author CHENCHEN
 * @title
 * @createTime 2023-02-27 22:05
 */
@RestControllerAdvice("com.cc.flyingfish")
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        if (methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class)) {
            //如果类上面有这个注解，不处理返回参数
            return false;
        }
        if (methodParameter.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class)) {
            //如果方法上面有这个注解，不处理返回参数
            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // 定义最终的返回对象
        CommonResponse response = SUCCESS;
        if (null == o) {
            return response;
        } else if (o instanceof CommonResponse) {
            return o;
        } else {
            response.setData(o);
        }
        return response;
    }
}
